from __future__ import print_function
import argparse
from math import log10

import os

import cv2
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
from matplotlib import pyplot as plt
from torch.autograd import Variable
from torch.utils.data import DataLoader
from dbpn import Net as DBPN
from dbpn_v1 import Net as DBPNLL
from dbpns import Net as DBPNS
from dbpns3 import Net as DBPNS3
from dbpn_iterative import Net as DBPNITER
from data import get_training_set
import pdb
import socket
import time

# Training settings
from eval import x8_forward, target_set
from utils import save_losses

parser = argparse.ArgumentParser(description='PyTorch Super Res Example')
parser.add_argument('--upscale_factor', type=int, default=4, help="super resolution upscale factor")
parser.add_argument('--batchSize', type=int, default=16, help='training batch size')  # wtl
parser.add_argument('--nEpochs', type=int, default=2000, help='number of epochs to train for')
parser.add_argument('--snapshots', type=int, default=10, help='Snapshots')  # wtl
parser.add_argument('--start_iter', type=int, default=1, help='Starting Epoch')
parser.add_argument('--lr', type=float, default=1e-4, help='Learning Rate. Default=0.01')
parser.add_argument('--gpu_mode', type=bool, default=True)
parser.add_argument('--threads', type=int, default=1, help='number of threads for data loader to use')
parser.add_argument('--seed', type=int, default=123, help='random seed to use. Default=123')
parser.add_argument('--gpus', default=1, type=int, help='number of gpu')
parser.add_argument('--data_dir', type=str, default='./Dataset')
parser.add_argument('--data_augmentation', type=bool, default=True)
parser.add_argument('--hr_train_dataset', type=str, default='DIV2K_train_HR')
parser.add_argument('--model_type', type=str, default='DBPNS')
parser.add_argument('--residual', type=bool, default=False)
parser.add_argument('--patch_size', type=int, default=40, help='Size of cropped HR image')
parser.add_argument('--pretrained_sr', default='DIV2K_train_HRDESKTOP-795A7TPDBPNStpami_residual_filter8_epoch_839.pth',
                    help='sr pretrained base model')
parser.add_argument('--pretrained', type=bool, default=True)
parser.add_argument('--save_folder', default='weights/', help='Location to save checkpoint models')
parser.add_argument('--prefix', default='tpami_residual_filter8', help='Location to save checkpoint models')

opt = parser.parse_args()
gpus_list = range(opt.gpus)
hostname = str(socket.gethostname())
cudnn.benchmark = True
print(opt)


def psnr(sr, hr):
    lossfunc = nn.MSELoss()
    mse = lossfunc(sr, hr)
    psnr = 10 * log10(1 / mse)
    return psnr


def save_img(img, img_name):
    save_img = img.squeeze().clamp(0, 1).numpy().transpose(1, 2, 0)
    # save img
    # save_dir = os.path.join(opt.output, opt.test_dataset)
    # if not os.path.exists(save_dir):
    #     os.makedirs(save_dir)

    save_fn = img_name
    cv2.imwrite(save_fn, cv2.cvtColor(save_img * 255, cv2.COLOR_BGR2RGB), [cv2.IMWRITE_PNG_COMPRESSION, 0])


epoch_loss_plot = []
avg_psnr_loss_plot = []


def train(epoch):
    epoch_loss = 0
    avg_psnr = 0
    model.train()
    for iteration, batch in enumerate(training_data_loader, 1):
        input, target, bicubic = Variable(batch[0]), Variable(batch[1]), Variable(batch[2])
        if cuda:
            input = input.cuda(gpus_list[0])
            target = target.cuda(gpus_list[0])
            bicubic = bicubic.cuda(gpus_list[0])

        optimizer.zero_grad()
        t0 = time.time()
        prediction = model(input)
        origin_pre = prediction

        if opt.residual:
            prediction = prediction + bicubic

        loss = criterion(prediction, target)
        t1 = time.time()
        epoch_loss += loss.data.cpu()
        loss.backward()
        optimizer.step()

        tmp_psnr = psnr(prediction, target)
        avg_psnr += tmp_psnr

        if iteration % 50 == 0:
            prediction_path = 'Results/train/' + '_*4_' + str(tmp_psnr) + '_' + opt.model_type + '_' + str(
                epoch) + '_' + str(
                iteration) + '.png'
            save_img(origin_pre.data[0].cpu(), prediction_path)

            if opt.residual:
                bicubic_path = 'Results/train/' + '_bicubic_' + opt.model_type + str(epoch) + '_' + str(
                    iteration) + '.png'
                save_img(bicubic.data[0].cpu(), bicubic_path)
                add_path = 'Results/train/' + '_added_prediction_' + opt.model_type + str(epoch) + '_' + str(
                    iteration) + '.png'
                save_img(prediction.data[0].cpu(), add_path)

            target_path = 'Results/train/' + '_*4' + '_target_' + opt.model_type + '_' + str(epoch) + '_' + str(
                iteration) + '.png'
            save_img(target.data[0].cpu(), target_path)
            # print('image saved')

        # print("psnr_loss:{}".format(tmp_psnr))  # wtl

        # print("===> Epoch[{}]({}/{}): Loss: {:.4f} || Timer: {:.4f} sec.".format(epoch, iteration,len(training_data_loader), loss.data,(t1 - t0)))
    avg_loss = epoch_loss / len(training_data_loader)
    epoch_loss_plot.append(avg_loss)
    save_losses(epoch_loss_plot, None, epoch)
    avg_psnr = avg_psnr / len(training_data_loader)
    avg_psnr_loss_plot.append(avg_psnr)

    plt.figure(figsize=(10, 5))
    plt.title("psnr_loss in train data")
    plt.plot(avg_psnr_loss_plot, label="avg_psnr")
    plt.xlabel("iterations")
    plt.ylabel("psnr")
    plt.legend()
    plt.savefig("result/psnr_loss_"+str(epoch)+".png")

    print("===> Epoch {} Complete: Avg. Loss: {:.4f}".format(epoch, avg_loss))
    print("avg_psnr:{}".format(avg_psnr))  # wtl


'''
def test():
    avg_psnr = 0
    for batch in testing_data_loader:
        input, target = Variable(batch[0]), Variable(batch[1])
        if cuda:
            input = input.cuda(gpus_list[0])
            target = target.cuda(gpus_list[0])

        prediction = model(input)
        mse = criterion(prediction, target)
        psnr = 10 * log10(1 / mse.data[0])
        avg_psnr += psnr
    print("===> Avg. PSNR: {:.4f} dB".format(avg_psnr / len(testing_data_loader)))
'''


def print_network(net):
    num_params = 0
    for param in net.parameters():
        num_params += param.numel()
    print(net)
    print('Total number of parameters: %d' % num_params)


def checkpoint(epoch):
    model_out_path = opt.save_folder + opt.hr_train_dataset + hostname + opt.model_type + opt.prefix + "_epoch_{}.pth".format(
        epoch)
    torch.save(model.state_dict(), model_out_path)
    print("Checkpoint saved to {}".format(model_out_path))


cuda = opt.gpu_mode
if cuda and not torch.cuda.is_available():
    raise Exception("No GPU found, please run without --cuda")

torch.manual_seed(opt.seed)
if cuda:
    torch.cuda.manual_seed(opt.seed)

print('===> Loading datasets')
train_set = get_training_set(opt.data_dir, opt.hr_train_dataset, opt.upscale_factor, opt.patch_size,
                             opt.data_augmentation)
training_data_loader = DataLoader(dataset=train_set, num_workers=opt.threads, batch_size=opt.batchSize, shuffle=True)

print('===> Building model ', opt.model_type)
if opt.model_type == 'DBPNLL':
    model = DBPNLL(num_channels=3, base_filter=64, feat=256, num_stages=10, scale_factor=opt.upscale_factor)
elif opt.model_type == 'DBPN-RES-MR64-3':
    model = DBPNITER(num_channels=3, base_filter=64, feat=256, num_stages=3, scale_factor=opt.upscale_factor)
elif opt.model_type == 'DBPNS':
    model = DBPNS(num_channels=3, base_filter=32, feat=128, num_stages=2, scale_factor=opt.upscale_factor)
elif opt.model_type == 'DBPNS3':
    model = DBPNS3(num_channels=3, base_filter=32, feat=128, num_stages=2, scale_factor=opt.upscale_factor)

model = torch.nn.DataParallel(model, device_ids=gpus_list)
criterion = nn.L1Loss()  # wtl

print('---------- Networks architecture -------------')
print_network(model)
print('----------------------------------------------')

if opt.pretrained:
    model_name = os.path.join(opt.save_folder + opt.pretrained_sr)
    if os.path.exists(model_name):
        # model= torch.load(model_name, map_location=lambda storage, loc: storage)
        model.load_state_dict(torch.load(model_name, map_location=lambda storage, loc: storage))
        print('Pre-trained SR model is loaded.')

if cuda:
    model = model.cuda(gpus_list[0])
    criterion = criterion.cuda(gpus_list[0])

optimizer = optim.Adam(model.parameters(), lr=opt.lr, betas=(0.9, 0.999), eps=1e-8)
# target_data_loader = DataLoader(dataset=target_set, num_workers=opt.threads, batch_size=opt.testBatchSize, shuffle=False)

for epoch in range(opt.start_iter, opt.nEpochs + 1):
    train(epoch)

    # learning rate is decayed by a factor of 10 every half of total epochs
    if (epoch + 1) % (opt.nEpochs / 2) == 0:
        for param_group in optimizer.param_groups:
            param_group['lr'] /= 10.0
        print('Learning rate decay: lr={}'.format(optimizer.param_groups[0]['lr']))

    if (epoch + 1) % (opt.snapshots) == 0:
        checkpoint(epoch)
        '''
        for index, batch in enumerate(target_data_loader, 1):
            _input = F.stop_gradient(batch['input_image'])
            t0 = time.time()
            if args.chop_forward:
                prediction = chop_forward(_input, model,
                                          args.upscale_factor)
            else:
                if args.self_ensemble:
                    prediction = x8_forward(_input, model)
                else:
                    prediction = model(_input)
            prediction = denorm(prediction[0], True)
            t1 = time.time()
            print("===> Processing: %d || Timer: %.4f sec." % (index, (t1 - t0)))
            save_img(prediction, str(index), 'Result/Gen/epoch%d' % epoch)
        '''
